package com.example.demo.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.bean.SDept;
import com.example.demo.bean.SRegion;
import com.example.demo.common.exception.DataValidException;
import com.example.demo.mapper.SDeptMapper;
import com.example.demo.mapper.SEmpMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class SDeptService {

	@Autowired
	private SDeptMapper sdMapper;
	@Autowired
	private SRegionService srService;
	@Autowired
	private SEmpMapper seMapper;
	//查找所有部门信息
	public PageInfo<SDept> findAllByPage(int pageNum,int pageSize){
		PageHelper.startPage(pageNum, pageSize);
		//执行查找行为
		List<SDept> list= sdMapper.selectAll();
		if (list==null) {
			list= new ArrayList<>(0);
		}
		return new PageInfo<>(list);
	}
	
	//按照条件查找部门信息
	public PageInfo<SDept> findByCondition(String name,Integer regionid,int pageNum,int pageSize){
		PageHelper.startPage(pageNum, pageSize);
		name=(name==null||"".equals(name))?"":"%"+name+"%";
		List<SDept> list=sdMapper.selectByCondition(name, regionid);
		if (list==null) {
			list = new ArrayList<>(0);
		}
		return new PageInfo<>(list);
	}
	
	//添加或修改部门信息
	public void saveOrUpdate(SDept sd) {
		//判断输入的信息是否存在
		if (sd==null) {
			throw new DataValidException("请填写信息");
		}
		//判断外键信息是否存在
		if (sd.getRegionId()==null) {
			throw new DataValidException("请填写完整信息不存在");
		}else {
			if (srService.findById(sd.getRegionId())==null) {
				throw new DataValidException("外键信息不存在");
			}
		}
		if (sd.getId()==null) {
			sdMapper.insert(sd);
		}else {
			sdMapper.updateByPrimaryKey(sd);
		}
	}
	//根据id删除部门信息
	//dept作为emp的外键存在
	//在删除dept前要判断其下属是否存在emp信息
	//不存在才可以删除
	public int deleteById(Integer id) {
		//判断id是否为空
		if (id==null) {
			throw new DataValidException("请输入顾客id");
		}
		//按照所给的id查找信息如果不存在报错
		if (sdMapper.selectByPrimaryKey(id)==null) {
			throw new DataValidException("删除失败");
		}
		//判断是否存在下属员工
		SDept sDept=sdMapper.selectByPrimaryKey(id);
		if (!seMapper.selectByDeptId(sDept.getId()).isEmpty()) {
			throw new DataValidException("要删除的信息下面存在员工信息，请删除响应的员工信息后在对其进行删除");
		}
		sdMapper.deleteByPrimaryKey(id);
		return 0;
	}
	//批量删除部门信息
	public int batchDeleteById(int[] id) {
		//判断是否为空
		if (id.length==0||id==null) {
			throw new DataValidException("请选择一批id");
		}
		for (int i : id) {
			if (sdMapper.selectByPrimaryKey(i)==null) {
				throw new DataValidException("删除失败");
			}
			//判断是否存在下属员工
			SDept sDept=sdMapper.selectByPrimaryKey(i);
			if (!seMapper.selectByDeptId(sDept.getId()).isEmpty()) {
				throw new DataValidException("要删除的信息下面存在员工信息，请删除响应的员工信息后在对其进行删除");
			}
		}
		//删除信息
		sdMapper.batchDelete(id);
		return 0;
	}
}
